#include <stdio.h>

#include "common.h"
#include "file.h"

#define CHUNK_SIZE 4096

int file_send(link_t* data, FILE* file)
{
	char buf[CHUNK_SIZE];
	int bytes_read = 0;

	DPRINT("[f] sending file...");

	do {
		bytes_read = fread(buf, 1, sizeof(buf), file);

		if (bytes_read > 0) {
			if (data_send(data, buf, bytes_read) != DATA_SUCCESS) {
				DPRINT("[f] failed to send buffer");
				return FILE_ERROR;
			}
		}
	} while(bytes_read > 0);

	if (!feof(file)) {
		DPRINT("[f] FAILED (couldn't send the entire file)");
		return FILE_ERROR;
	}

	DPRINT("[f] OK");

	DPRINT("[f] closing data connecting"); /* send "EOF" */
	link_close(data);

	return FILE_SUCCESS;
}

int file_recv(link_t* data, FILE* file)
{
	char buf[CHUNK_SIZE];
	int ret;

	DPRINT("[f] receiving file...");

	do {
		int bytes_recved;
		ret = data_receive(data, buf, sizeof(buf), &bytes_recved);
		
		if (ret == DATA_SUCCESS) {
			if (bytes_recved != fwrite(buf, 1, bytes_recved, file)) {
				DPRINT("[f] FAILED (couldn't write to local file)");
				return FILE_ERROR;
			}
		}
	} while (ret == DATA_SUCCESS);

	fflush(file);

	/* LINK_DISCONNECTED == EOF, otherwise error */
	if (DATA_DISCONNECTED != ret) {
		DPRINT("[f] FAILED (couldn't receive the entire file)");
		return FILE_ERROR;
	}
	else {
		DPRINT("[f] OK");

		DPRINT("[f] closing data connecting"); /* will not be used anymore */
		link_close(data);
	}	

	return FILE_SUCCESS;
}
